package com.neu.util;

import android.graphics.Bitmap;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.neu.view.App;
import com.neu.R;


import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * Volley网络访问工具类
 * 出现错误
 * 有时候需要设置
 * <uses-library android:name="org.apache.http.legacy" android:required="false" />
 *
 */
public class VolleyUtil {
    private static String TAG="vu";
    public static String BASE_URL="http://124.93.196.45:10001";
    public static String TOKEN=null;
    public BackJson backJson;

    /**
     *
     * @param method 网络访问方法 get post put Requst.
     * @param url 接口的方法
     * @param param post put以json的格式提交参数
     * @param backJson 回调方法，在此接受数据
     */
    public static   void  request(int method,String url, Map<String,String> param, final BackJson backJson){
      final   JSONObject jb=new JSONObject();
        try {
            if(param!=null){
                for(String key:param.keySet()){
                    jb.put(key,param.get(key));
                }
                Log.d(TAG, "参数: " + jb.toString());
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

        JsonObjectRequest jr=new JsonObjectRequest(method,
                BASE_URL + url, jb,new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                String json = jsonObject.toString();
                Log.d(TAG, "onResponse: " + json);
                App.sRequsetQueue.getCache().clear();
                backJson.success(json);

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                volleyError.printStackTrace();
                Toast.makeText(App.context,volleyError.getMessage(),Toast.LENGTH_LONG).show();
            }
        })

        {
            //重写方法添加Header信息
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                final Map<String, String> headers = new HashMap<>();
                if(TOKEN!=null) {
                    headers.put("Authorization", "Bearer " + TOKEN);
                    headers.put("Content-Type", "application/json");
                }
                return headers;
            }
        };

        App.sRequsetQueue.add(jr);
    }



    /**
     * 获得网络图片
     * @param url 网络图片地址（接口中返回的地址）
     * @param imageView 图片对象
     */
    public static void getImage(String url, final ImageView imageView){
        ImageRequest imageRequest = new ImageRequest(
                url,
                new Response.Listener<Bitmap>() {
                    @Override
                    public void onResponse(Bitmap response) {
                        imageView.setImageBitmap(response);
                    }
                }, 0, 0, Bitmap.Config.RGB_565, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                imageView.setImageResource(R.drawable.ic_launcher_foreground);
            }
        });

        App.sRequsetQueue.add(imageRequest);

    }


    public interface BackJson{
        void success(String json);
    }
}
